//
//  MixedPanel.m
//  RSW.IOS
//
//  Created by zhaiqiuqiu on 17/1/7.
//  Copyright © 2017年 com.xtion.crm. All rights reserved.
//

#import "MixedPanel.h"
#import "XUIPanelWindow.h"
#import "MixedPanelGroupTableViewCell.h"

#define FuncationPanelFunctionBtnWidth          50.0
#define FuncationPanelFunctionBtnHeight         80.0
#define FuncationPanelFunctionBtnImageWidth         50.0
#define FuncationPanelFunctionBtnImageHeight         FuncationPanelFunctionBtnImageWidth

#define FuncationPanelBtnleftRightBorderMargin      20.0
#define FuncationPanelBtnTopBottomBorderMargin      20.0

NSUInteger const AddMixedImageButtonTag = 10000;
NSUInteger const DeleteMixedImageButtonTag = 20000;


NSUInteger const RecordMixedImageButtonTag = 30000;

@interface MixedPanel()<FunctionPanelDelegate,UIScrollViewDelegate>
{
    __weak MixedPanelGroupTableViewCell *_mixedPanelGroupTableViewCell;
    UIScrollView *_scroll;
}
@end

@implementation MixedPanel

-(id)initWithFrame:(CGRect)frame mixedPanelGroupTableViewCell:(MixedPanelGroupTableViewCell*)mixedPanelGroupTableViewCell
{
    self = [super initWithFrame:frame];
    
    _mixedPanelGroupTableViewCell = mixedPanelGroupTableViewCell;
    
    _contain = [NSMutableArray new];
    
    _hiddenDeleteTag = YES;
    
    _addImageBtn = [[MixedImageButton alloc]initWithFrame:CGRectMake(10, 10, frame.size.height - 10 - 10, frame.size.height - 10 - 10)];
    _addImageBtn.image = [UIImage imageNamed:@"headviewpanel_add.png"];
    _addImageBtn.tag = AddMixedImageButtonTag;
    [self addSubview:_addImageBtn];
    
    [_contain addObject:_addImageBtn];
    
    _deleteImageBtn = [[MixedImageButton alloc]initWithFrame:CGRectMake(_addImageBtn.right + 15, 10, frame.size.height - 10 - 10, frame.size.height - 10 - 10)];
    _deleteImageBtn.image = [UIImage imageNamed:@"headviewpanel_delete.png"];
    _deleteImageBtn.tag = DeleteMixedImageButtonTag;
    _deleteImageBtn.hidden = YES;
    [self addSubview:_deleteImageBtn];
    
    [_contain addObject:_deleteImageBtn];
    
    _scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, _addImageBtn.left, frame.size.height - 10)];
    _scroll.backgroundColor = [UIColor clearColor];
    _scroll.delegate = self;
    _scroll.showsHorizontalScrollIndicator = NO; 
    [self addSubview:_scroll];
    
    return self;
}

-(void)setHiddenDeleteTag:(BOOL)hiddenDeleteTag
{
    _hiddenDeleteTag = hiddenDeleteTag;
    
    _deleteMode = !hiddenDeleteTag;
}

-(NSUInteger)imageCount
{
    NSMutableArray *ar = [_contain mutableCopy];
    [ar removeObject:_addImageBtn];
    [ar removeObject:_deleteImageBtn];
    return ar.count;
}

-(void)layoutSubviews
{
    [super layoutSubviews];

    [self calcute];
}

-(void)calcute
{
    if(_contain.count <= 2)
    {
        _scroll.width = 10;
        _scroll.contentSize = CGSizeMake(0, 0);
    }
    else
    {
        MixedImageButton *imageBtn = _contain[_contain.count - 3];
        if(imageBtn.right > _scroll.width)
        {
            _scroll.contentSize = CGSizeMake(imageBtn.right + 10, 0);
        }
        else
        {
            _scroll.width = imageBtn.right + 10;
            _scroll.contentSize = CGSizeMake(0, 0);
        }
    }
    
    _addImageBtn.left = _scroll.right + 5;
    _deleteImageBtn.left = _addImageBtn.right + 15;
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    
    for(MixedImageButton *imgBtn in _contain)
    {
        if(imgBtn.tag == AddMixedImageButtonTag && _addImageBtn.hidden == NO)
        {
            if(CGRectContainsPoint(imgBtn.frame, [touch locationInView:self]))
            {
                if([_mixedDelegate respondsToSelector:@selector(clickAddImageButtonOfMixedPanel:)])
                    [_mixedDelegate clickAddImageButtonOfMixedPanel:self];
                break;
            }
        }
        else if(imgBtn.tag == DeleteMixedImageButtonTag && _deleteImageBtn.hidden == NO)
        {
            if(CGRectContainsPoint(imgBtn.frame, [touch locationInView:self]))
            {
                for(MixedImageButton *imgBtn in _contain)
                {
                    if(imgBtn != _addImageBtn && imgBtn != _deleteImageBtn)
                    {
                        imgBtn.hiddenDeleteTag = _deleteMode;
                    }
                }
                
                _deleteMode = !_deleteMode;
                
                if([_mixedDelegate respondsToSelector:@selector(clickDeleteImageButtonOfMixedPanel:)])
                    [_mixedDelegate clickDeleteImageButtonOfMixedPanel:self];
                
                break;
            }
        }
        else if(imgBtn.tag != AddMixedImageButtonTag && imgBtn.tag != DeleteMixedImageButtonTag)
        {
            CGRect deleteTagFrame = [self convertRect:imgBtn.deleteImageView.frame fromView:imgBtn];
            CGRect addBtnFrame = _addImageBtn.frame;
            CGRect deleteBtnFrame = _deleteImageBtn.frame;
            
            if(CGRectContainsPoint(addBtnFrame, [touch locationInView:self]))
            {
                continue;
            }
            
            if(CGRectContainsPoint(deleteBtnFrame, [touch locationInView:self]))
            {
                continue;
            }
            
            if(CGRectContainsPoint(deleteTagFrame, [touch locationInView:_scroll])
               || (CGRectContainsPoint(imgBtn.frame, [touch locationInView:_scroll])))
            {
                if(_deleteMode == YES)
                {
                    [_mixedDelegate clickDeleteModeImageButtonOfMixedPanel:self atTag:imgBtn.szTag];
                }
                else
                {
                    if([_mixedDelegate respondsToSelector:@selector(mixedPanel:didClickedImageButton:imageContains:)])
                    {
                        NSMutableArray *ar = [_contain mutableCopy];
                        [ar removeObject:_addImageBtn];
                        [ar removeObject:_deleteImageBtn];
                        [_mixedDelegate mixedPanel:self didClickedImageButton:imgBtn imageContains:ar];
                    }
                }
                break;
            }
        }
    }
}

-(void)addImage:(UIImage*)image withTag:(NSString*)tag
{
    [self exitDeleteMode];
    
    image = [UIImage imageFromImage:image size:_addImageBtn.size fillStyle:EImageFillStyleStretchByCenterScale];
    
    MixedImageButton *imgBtn = [[MixedImageButton alloc]initWithFrame:_addImageBtn.frame];
    imgBtn.szTag = tag;
    imgBtn.hiddenDeleteTag = _hiddenDeleteTag;
    imgBtn.image = image;
    [_scroll addSubview:imgBtn];
    
    NSUInteger index = [_contain indexOfObject:_addImageBtn];
    if(index != NSNotFound)
        [_contain insertObject:imgBtn atIndex:index];
    else
        [_contain addObject:imgBtn];
    
    self.userInteractionEnabled = NO;
    [UIView animateWithDuration:0.25 animations:^
     {
         CGFloat x = 10;
         BOOL isScroll = NO;
         for(NSInteger i = 0; i < _contain.count - 2;i++)
         {
             MixedImageButton *imgBtn = _contain[i];
             imgBtn.left = x;
             x += imgBtn.width + 15;
             
             if(x > (self.width - 125))
             {
                 _scroll.width = self.width - 125;
                 isScroll = YES;
             }
             else
             {
                 _scroll.width = x;
             }
         }
         
         if(_contain.count >= 10)
         {
             _deleteImageBtn.frame = _addImageBtn.frame;
             _addImageBtn.hidden = YES;
         }
         
         if(isScroll == YES)
         {
             _scroll.contentSize = CGSizeMake(x, 0);
             _scroll.contentOffset = CGPointMake(0, 0);
         }
     } completion:^(BOOL finished)
     {
         self.userInteractionEnabled = YES;
     }];

    _deleteImageBtn.hidden = NO;
}

-(void)replaceImage:(UIImage*)image withTag:(NSString*)tag
{
    image = [UIImage imageFromImage:image size:_addImageBtn.size fillStyle:EImageFillStyleStretchByCenterScale];
    for(NSInteger i = 0; i < _contain.count;i++)
    {
        MixedImageButton *imageBtn = _contain[i];
        if([imageBtn.szTag isEqualToString:tag])
        {
            imageBtn.image = image;
            break;
        }
    }
}

-(void)deleteImageWithTag:(NSString*)szTag
{
    for(NSInteger i = 0; i < _contain.count; i++)
    {
        MixedImageButton *imgBtn = _contain[i];
        if([imgBtn.szTag isEqualToString:szTag])
        {
            CGRect frame = imgBtn.frame;
            for(NSInteger j = i + 1; j< _contain.count - 2 ;j++)
            {
                MixedImageButton *imgBtn = _contain[j];
                CGRect f = imgBtn.frame;
                imgBtn.frame = frame;
                frame = f;
            }
            [imgBtn removeFromSuperview];
            [_contain removeObject:imgBtn];
            
            if(_contain.count <10)
                _addImageBtn.hidden = NO;
            
            break;
        }
    }
    
    if(_contain.count <= 2)
        _deleteImageBtn.hidden = YES;
    
    if(_contain.count <= 2)
        [self exitDeleteMode];
    
    [self calcute];
    //[self setNeedsLayout];
}

-(void)exitDeleteMode
{
    if(_hiddenDeleteTag == NO)
        return;
    
    for(MixedImageButton *imgBtn in _contain)
    {
        if(imgBtn != _addImageBtn && imgBtn != _deleteImageBtn)
        {
            imgBtn.hiddenDeleteTag = YES;
        }
    }
    
    _deleteMode = NO;
}

-(void)show
{
    [FunctionPanelView functionPanelViewWithDelegate:self];
}

- (void)mixedPanel:(FunctionPanelView *)panel clickFileBtn:(id)sender
{
    [UIViewController closeKeyBoard];
    
    //TODO
}

- (void)mixedPanel:(FunctionPanelView *)panel clickPhotoAlbumBtn:(id)sender
{
    [UIViewController closeKeyBoard];

    [(id<MixedPanelGroupTableViewCellDelegate>)_mixedPanelGroupTableViewCell.delegate clickAddButtonOfMixedPanelGroupTableViewCell:_mixedPanelGroupTableViewCell mixedTyp:MixedPanelFunctionPanelTypePhotoAlbum];
}

- (void)mixedPanel:(FunctionPanelView *)panel clickTakePhotoBtn:(id)sender
{
    [UIViewController closeKeyBoard];
    
    [(id<MixedPanelGroupTableViewCellDelegate>)_mixedPanelGroupTableViewCell.delegate clickAddButtonOfMixedPanelGroupTableViewCell:_mixedPanelGroupTableViewCell mixedTyp:MixedPanelFunctionPanelTypeTakePhoto];
}

- (void)mixedPanel:(FunctionPanelView *)panel clickVoiceBtn:(id)sender
{
    [UIViewController closeKeyBoard];
    
    [(id<MixedPanelGroupTableViewCellDelegate>)_mixedPanelGroupTableViewCell.delegate clickAddButtonOfMixedPanelGroupTableViewCell:_mixedPanelGroupTableViewCell mixedTyp:MixedPanelFunctionPanelTypeVoice];
}

- (void)mixedPanel:(FunctionPanelView *)panel clickRecordBtn:(id)sender
{
    [UIViewController closeKeyBoard];
    
     [(id<MixedPanelGroupTableViewCellDelegate>)_mixedPanelGroupTableViewCell.delegate clickAddButtonOfMixedPanelGroupTableViewCell:_mixedPanelGroupTableViewCell mixedTyp:MixedPanelFunctionPanelTypeRecord];
}

- (void)mixedPanel:(FunctionPanelView *)panel clickPositionBtn:(id)sender
{
    [UIViewController closeKeyBoard];
    
    [(id<MixedPanelGroupTableViewCellDelegate>)_mixedPanelGroupTableViewCell.delegate clickAddButtonOfMixedPanelGroupTableViewCell:_mixedPanelGroupTableViewCell mixedTyp:MixedPanelFunctionPanelTypePosition];
}

@end

@interface FunctionPanelView()<XUIButtonDelegate,UIGestureRecognizerDelegate>
{
    XUIPanelWindow *_window;

    id<FunctionPanelDelegate> _delegate;
    
    UIScrollView *_functionPanel;
    
    UIImageView *_backgroundImageView;
}
@end

@implementation FunctionPanelView

- (id)initWithDelegate:(id<FunctionPanelDelegate>)delegate
{
    self = [super initWithFrame:CGRectZero];
    self.backgroundColor = [UIColor colorWithR:0 G:0 B:0 A:0.6];
    
    _delegate = delegate;
    
    [self initUI];
    
    return self;
}

+(void)functionPanelViewWithDelegate:(id<FunctionPanelDelegate>)delegate
{
    FunctionPanelView *view = [[FunctionPanelView alloc]initWithDelegate:delegate];
    
    [view show];
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    _functionPanel.width = self.width;
    _backgroundImageView.frame = _functionPanel.frame;
}

- (void)show
{
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    
    _window = [XUIPanelWindow new];
    _window.responder = self;
    
    self.frame = _window.bounds;
    
    self.alpha = 0;
    _functionPanel.top = self.height;
    
    keyWindow.userInteractionEnabled = NO;
    
    [UIView animateWithDuration:0.3 animations:^
     {
         _functionPanel.bottom = self.height;
         self.alpha = 1;
         
     } completion:^(BOOL finished)
     {
         keyWindow.userInteractionEnabled = YES;
     }];
}

- (void)initUI
{
    UIImage *background = [[UIImage imageNamed:@"input_background.png"] resizeableCenterImage];
    _backgroundImageView = [[UIImageView alloc] initWithImage:background];
    _backgroundImageView.frame = CGRectMake(0, 0, 0, 0);
    [self addSubview:_backgroundImageView];
    
    _functionPanel = [[UIScrollView alloc]initWithFrame:CGRectMake(self.left, self.bottom, self.width, 216)];
    _functionPanel.backgroundColor = [UIColor colorWithR:227 G:227 B:227 A:1];
    
    [self addSubview:_functionPanel];
    
    __block CGFloat x = FuncationPanelBtnleftRightBorderMargin;
    __block CGFloat y = FuncationPanelBtnTopBottomBorderMargin;
    
    XMSQueueDictionary *qd = [XMSQueueDictionary new];
    //[qd addKey:@"文件" value:[XMSKvPair kvPairWithKey:@(MixedPanelFunctionPanelTypeFile) value:[UIImage imageNamed:@"input_function_photoalbum.png"]]];
    
    [qd addKey:@"图片" value:[XMSKvPair kvPairWithKey:@(MixedPanelFunctionPanelTypePhotoAlbum) value:[UIImage imageNamed:@"input_function_photoalbum.png"]]];
    
    [qd addKey:@"拍照" value:[XMSKvPair kvPairWithKey:@(MixedPanelFunctionPanelTypeTakePhoto) value:[UIImage imageNamed:@"input_function_takephoto.png"]]];
    
    [qd addKey:@"录音" value:[XMSKvPair kvPairWithKey:@(MixedPanelFunctionPanelTypeVoice) value:[UIImage imageNamed:@"input_function_voice.png"]]];
    
    [qd addKey:@"录像" value:[XMSKvPair kvPairWithKey:@(MixedPanelFunctionPanelTypeRecord) value:[UIImage imageNamed:@"input_function_record.png"]]];
    
    //[qd addKey:@"位置" value:[XMSKvPair kvPairWithKey:@(MixedPanelFunctionPanelTypePosition) value:[UIImage imageNamed:@"input_function_position.png"]]];
    
    [qd enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
     {
         XMSKvPair *pair = obj;
         NSString *title = pair.idKey;
         MixedPanelFunctionPanelType type = [[pair.idValue idKey] integerValue];
         
         XUIButton *btn = [XUIButton buttonWithStyleType:XUIButtonStyleTypeTopHeadImage delegate:self];
         btn.frame = CGRectMake(x, y, FuncationPanelFunctionBtnWidth, FuncationPanelFunctionBtnHeight);
         btn.backgroundColor = [UIColor clearColor];
         [btn SetImage:[pair.idValue idValue]];
         [btn SetTitle:title];
         btn.szTag = [NSString stringWithFormat:@"%@",@(type)];
         [_functionPanel addSubview:btn];
         
         x += btn.width + FuncationPanelBtnleftRightBorderMargin;
         
         if(x > self.width)
         {
             _functionPanel.contentSize = CGSizeMake(x, 0);
         }
     }];
    
    y = ((UIView*)_functionPanel.subviews[_functionPanel.subviews.count - 1]).bottom + FuncationPanelBtnTopBottomBorderMargin;
    
    _functionPanel.top = self.height;
    _functionPanel.height = MIN( 216 + self.height , y);
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureRecognizer:)];
    tap.delegate = self;
    [self addGestureRecognizer:tap];
}

-(void)close
{
    self.superview.userInteractionEnabled = NO;
    
    [UIView animateWithDuration:0.3 animations:^
     {
         self.top = [self superview].bottom;
         self.alpha = 0;
         
     } completion:^(BOOL finished)
     {
         self.superview.userInteractionEnabled = YES;
         
         [self removeFromSuperview];
         
         _window = nil;
     }];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    CGPoint p = [touch locationInView:self];
    if (CGRectContainsPoint(_functionPanel.frame, p) == YES)
        return NO;
    return YES;
}

- (void)tapGestureRecognizer:(UITapGestureRecognizer *)gr
{
    [self close];
}

-(void)clickedUpInsideOfButton:(XUIButton *)btn
{
    switch([btn.szTag intValue])
    {
        case MixedPanelFunctionPanelTypeFile:
        {
            if([_delegate respondsToSelector:@selector(mixedPanel:clickFileBtn:)])
            {
                [self close];
                [_delegate mixedPanel:self clickFileBtn:nil];
            }
            break;
        }
        case MixedPanelFunctionPanelTypePhotoAlbum:
        {
            if([_delegate respondsToSelector:@selector(mixedPanel:clickPhotoAlbumBtn:)])
            {
                [self close];
                [_delegate mixedPanel:self clickPhotoAlbumBtn:nil];
            }
            break;
        }
        case MixedPanelFunctionPanelTypeTakePhoto:
        {
            if([_delegate respondsToSelector:@selector(mixedPanel:clickTakePhotoBtn:)])
            {
                [self close];
                [_delegate mixedPanel:self clickTakePhotoBtn:nil];
            }
            break;
        }
        case MixedPanelFunctionPanelTypeVoice:
        {
            if([_delegate respondsToSelector:@selector(mixedPanel:clickVoiceBtn:)])
            {
                [self close];
                [_delegate mixedPanel:self clickVoiceBtn:nil];
            }
            break;
        }
        case MixedPanelFunctionPanelTypeRecord:
        {
            if([_delegate respondsToSelector:@selector(mixedPanel:clickRecordBtn:)])
            {
                [self close];
                [_delegate mixedPanel:self clickRecordBtn:nil];
            }
            break;
        }
        case MixedPanelFunctionPanelTypePosition:
        {
            if([_delegate respondsToSelector:@selector(mixedPanel:clickPositionBtn:)])
            {
                //[self close];
                //[_delegate mixedPanel:self clickPositionBtn:nil];
            }
            break;
        }
    }
}
@end
